package com.basker.pisces.domain.property.meta;

import org.apache.commons.codec.digest.DigestUtils;

import com.basker.pisces.core.meta.annotation.DataField;
import com.basker.pisces.domain.property.InvalidPropertyValueException;
import com.basker.pisces.domain.value.PasswordValue;

/**
 * 密码属性，外部赋值的明文会被指定算法加密
 *
 * @author hangwen
 */
public class PasswordProperty extends Property<PasswordValue> {

    @DataField
    private EncryptType encryptType;

    @Override
    public PasswordValue createValue(Object rawValue) {
        return new PasswordValue(rawValue);
    }

    public String encryptInputValue(Object inputValue) {
        String password = inputValue != null ? String.valueOf(inputValue) : null;
        EncryptType encryptType2Use = encryptType != null ? encryptType : EncryptType.MD5;

        if (EncryptType.MD5 == encryptType2Use) {
            return DigestUtils.md5Hex(password);
        } else {
            return DigestUtils.sha1Hex(password);
        }
    }

    public EncryptType getEncryptType() {
        return encryptType;
    }

    public void setEncryptType(EncryptType encryptType) {
        this.encryptType = encryptType;
    }

    @Override
    public void setValue(Object dataObject, Object inputValue) throws InvalidPropertyValueException {
        String encrypt = this.encryptInputValue(inputValue);
        this.setRawValue(dataObject, encrypt);
    }

    public static enum EncryptType {
        SHA1, MD5
    }

}
